use crate::REQWEST_CLIENT;
use anyhow::Result;
use serde::{ Deserialize, Serialize };
use serde_json::Value;
/// Mapping to [RPT_PCF10_ORG_ISSUEINFO.json](file:///Users/CC/gitee/conanchen/fuquants-workspace/crates/fudacli/eastmoney/sample/RPT_PCF10_ORG_ISSUEINFO.json)
#[derive(Debug, Serialize, Deserialize)]
pub struct RptF10BasicOrgIssue {
    pub version: Value,
    pub result: RptF10BasicOrgIssueResult,
    pub success: Value,
    pub message: Value,
    pub code: Value,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RptF10BasicOrgIssueResult {
    pub pages: Value,
    pub data: Vec<RptF10BasicOrgIssueResultData>,
    pub count: Option<Value>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RptF10BasicOrgIssueResultData {
    #[serde(rename = "SECUCODE")]
    pub secucode: Option<Value>, // 证券代码
    #[serde(rename = "SECURITY_CODE")]
    pub security_code: Option<Value>, // 证券代码（可能是另一种格式或用途）
    #[serde(rename = "FOUND_DATE")]
    pub found_date: Option<Value>, // 成立日期
    #[serde(rename = "LISTING_DATE")]
    pub listing_date: Option<Value>, // 上市日期
    #[serde(rename = "AFTER_ISSUE_PE")]
    pub after_issue_pe: Option<Value>, // 发行后市盈率
    #[serde(rename = "ONLINE_ISSUE_DATE")]
    pub online_issue_date: Option<Value>, // 网上发行日期
    #[serde(rename = "ISSUE_WAY")]
    pub issue_way: Option<Value>, // 发行方式
    #[serde(rename = "PAR_VALUE")]
    pub par_value: Option<Value>, // 面值
    #[serde(rename = "TOTAL_ISSUE_NUM")]
    pub total_issue_num: Option<Value>, // 总发行数量
    #[serde(rename = "ISSUE_PRICE")]
    pub issue_price: Option<Value>, // 发行价格
    #[serde(rename = "DEC_SUMISSUEFEE")]
    pub dec_sumissuefee: Option<Value>, // 发行总费用（可能是经过某种计算的费用）
    #[serde(rename = "TOTAL_FUNDS")]
    pub total_funds: Option<Value>, // 总募集资金
    #[serde(rename = "NET_RAISE_FUNDS")]
    pub net_raise_funds: Option<Value>, // 净募集资金
    #[serde(rename = "OPEN_PRICE")]
    pub open_price: Option<Value>, // 开盘价
    #[serde(rename = "CLOSE_PRICE")]
    pub close_price: Option<Value>, // 收盘价
    #[serde(rename = "TURNOVERRATE")]
    pub turnover_rate: Option<Value>, // 换手率
    #[serde(rename = "HIGH_PRICE")]
    pub high_price: Option<Value>, // 最高价
    #[serde(rename = "OFFLINE_VAP_RATIO")]
    pub offline_vap_ratio: Option<Value>, // 网下配售比例
    #[serde(rename = "ONLINE_ISSUE_LWR")]
    pub online_issue_lwr: Option<Value>, // 网上发行中签率
}

impl RptF10BasicOrgIssue {
    /// code: 000001.SZ or 600519.SH
    ///
    // Referer: https://emweb.securities.eastmoney.com/pc_hsf10/pages/index.html?type=web&code=SZ000001&color=b#/gsgk
    //
    // Data: https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_PCF10_ORG_ISSUEINFO&columns=SECUCODE%2CSECURITY_CODE%2CFOUND_DATE%2CLISTING_DATE%2CAFTER_ISSUE_PE%2CONLINE_ISSUE_DATE%2CISSUE_WAY%2CPAR_VALUE%2CTOTAL_ISSUE_NUM%2CISSUE_PRICE%2CDEC_SUMISSUEFEE%2CTOTAL_FUNDS%2CNET_RAISE_FUNDS%2COPEN_PRICE%2CCLOSE_PRICE%2CTURNOVERRATE%2CHIGH_PRICE%2COFFLINE_VAP_RATIO%2CONLINE_ISSUE_LWR&quoteColumns=&filter=(SECUCODE%3D%22000001.SZ%22)&pageNumber=1&pageSize=1&sortTypes=&sortColumns=&source=HSF10&client=PC&v=0501819038128587
    pub async fn rpt_f10_basic_orgissue(code: &str) -> Result<RptF10BasicOrgIssue> {
        println!(
            "\nGet Data: https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_PCF10_ORG_ISSUEINFO&columns=SECUCODE%2CSECURITY_CODE%2CFOUND_DATE%2CLISTING_DATE%2CAFTER_ISSUE_PE%2CONLINE_ISSUE_DATE%2CISSUE_WAY%2CPAR_VALUE%2CTOTAL_ISSUE_NUM%2CISSUE_PRICE%2CDEC_SUMISSUEFEE%2CTOTAL_FUNDS%2CNET_RAISE_FUNDS%2COPEN_PRICE%2CCLOSE_PRICE%2CTURNOVERRATE%2CHIGH_PRICE%2COFFLINE_VAP_RATIO%2CONLINE_ISSUE_LWR&quoteColumns=&filter=(SECUCODE%3D%22{code}%22)&pageNumber=1&pageSize=1&sortTypes=&sortColumns=&source=HSF10&client=PC&v=0501819038128587"
        );
        // GET /securities/api/data/v1/get?reportName=RPT_PCF10_ORG_ISSUEINFO&columns=SECUCODE%2CSECURITY_CODE%2CFOUND_DATE%2CLISTING_DATE%2CAFTER_ISSUE_PE%2CONLINE_ISSUE_DATE%2CISSUE_WAY%2CPAR_VALUE%2CTOTAL_ISSUE_NUM%2CISSUE_PRICE%2CDEC_SUMISSUEFEE%2CTOTAL_FUNDS%2CNET_RAISE_FUNDS%2COPEN_PRICE%2CCLOSE_PRICE%2CTURNOVERRATE%2CHIGH_PRICE%2COFFLINE_VAP_RATIO%2CONLINE_ISSUE_LWR&quoteColumns=&filter=(SECUCODE%3D%22000001.SZ%22)&pageNumber=1&pageSize=1&sortTypes=&sortColumns=&source=HSF10&client=PC&v=0501819038128587 HTTP/1.1
        // Accept: */*
        // Accept-Encoding: gzip, deflate, br
        // Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
        // Cache-Control: no-cache
        // Connection: keep-alive
        // Host: datacenter.eastmoney.com
        // Origin: https://emweb.securities.eastmoney.com
        // Pragma: no-cache
        // Referer: https://emweb.securities.eastmoney.com/
        // Sec-Fetch-Dest: empty
        // Sec-Fetch-Mode: cors
        // Sec-Fetch-Site: same-site
        // User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
        // sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"
        // sec-ch-ua-mobile: ?0
        // sec-ch-ua-platform: "macOS"

        // Query String Parameters:
        //
        // reportName: RPT_PCF10_ORG_ISSUEINFO
        // columns: SECUCODE,SECURITY_CODE,FOUND_DATE,LISTING_DATE,AFTER_ISSUE_PE,ONLINE_ISSUE_DATE,ISSUE_WAY,PAR_VALUE,TOTAL_ISSUE_NUM,ISSUE_PRICE,DEC_SUMISSUEFEE,TOTAL_FUNDS,NET_RAISE_FUNDS,OPEN_PRICE,CLOSE_PRICE,TURNOVERRATE,HIGH_PRICE,OFFLINE_VAP_RATIO,ONLINE_ISSUE_LWR
        // quoteColumns:
        // filter: (SECUCODE="000001.SZ")
        // pageNumber: 1
        // pageSize: 1
        // sortTypes:
        // sortColumns:
        // source: HSF10
        // client: PC
        // v: 0501819038128587

        let request_url = format!(
            "https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_PCF10_ORG_ISSUEINFO&columns=SECUCODE%2CSECURITY_CODE%2CFOUND_DATE%2CLISTING_DATE%2CAFTER_ISSUE_PE%2CONLINE_ISSUE_DATE%2CISSUE_WAY%2CPAR_VALUE%2CTOTAL_ISSUE_NUM%2CISSUE_PRICE%2CDEC_SUMISSUEFEE%2CTOTAL_FUNDS%2CNET_RAISE_FUNDS%2COPEN_PRICE%2CCLOSE_PRICE%2CTURNOVERRATE%2CHIGH_PRICE%2COFFLINE_VAP_RATIO%2CONLINE_ISSUE_LWR&quoteColumns=&filter=(SECUCODE%3D%22{code}%22)&pageNumber=1&pageSize=1&sortTypes=&sortColumns=&source=HSF10&client=PC&v=0501819038128587"
        );
        let response = REQWEST_CLIENT.get(request_url)
            .header(reqwest::header::ACCEPT, "*/*")
            .header(reqwest::header::ACCEPT_ENCODING, "gzip, deflate, br")
            .header(reqwest::header::ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8")
            .header(reqwest::header::CACHE_CONTROL, "no-cache")
            .header(reqwest::header::CONNECTION, "keep-alive")
            // .header(reqwest::header::COOKIE, "qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-16%2016%3A57%3A06@%23%24%u4E2D%u822A%u65B0%u8D77%u822A%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408A@%23%24005537; EMFUND1=01-16%2017%3A04%3A53@%23%24%u91D1%u4FE1%u6D88%u8D39%u5347%u7EA7%u80A1%u7968A@%23%24006692; EMFUND2=01-16%2020%3A01%3A56@%23%24%u5357%u65B9%u4E0A%u8BC1380ETF@%23%24510290; EMFUND3=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND4=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND5=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND6=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND7=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND8=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND9=02-02 10:30:22@#$%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; st_asi=delete; HAList=ty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-002400-%u7701%u5E7F%u96C6%u56E2%2Cty-1-601127-%u8D5B%u529B%u65AF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=438; st_psi=20240226102321941-113200301321-9024721593")
            .header(reqwest::header::HOST, "datacenter.eastmoney.com")
            .header(reqwest::header::ORIGIN, "https://emweb.securities.eastmoney.com")
            .header(reqwest::header::PRAGMA, "no-cache")
            .header(reqwest::header::REFERER, "https://emweb.securities.eastmoney.com/")
            .header(
                reqwest::header::USER_AGENT,
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
            )
            .header(
                "Sec-Ch-Ua",
                "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\""
            )
            .header("Sec-Ch-Ua-Mobile", "?0")
            .header("Sec-Ch-Ua-Platform", "\"macOS\"")
            .header("Sec-Fetch-Dest", "empty")
            .header("Sec-Fetch-Mode", "cors")
            .header("Sec-Fetch-Site", "same-origin")
            .send().await?;

        let body = response.text().await?;

        // println!("*** body={}\n\nhangqin\n\n", body);

        let fund: RptF10BasicOrgIssue = serde_json::from_str(&body)?;

        // println!("{:?}", fund);

        Ok(fund)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    async fn test_stock_rpt_f10_basic_orginfo() {
        let result = RptF10BasicOrgIssue::rpt_f10_basic_orgissue("000001.SZ").await;

        assert_eq!(result.is_ok(), true);
        if let Ok(basic_org_issue) = result {
            assert_eq!(basic_org_issue.message.as_str(), Some("ok"));
            println!("{:?}\n", basic_org_issue);
        }
    }
}
